package com.thundersoft.pickcolor.activity;

import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MenuItem;

import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.thundersoft.pickcolor.R;
import com.thundersoft.pickcolor.adapter.ColorAdapter;
import com.thundersoft.pickcolor.bean.Color;
import com.thundersoft.pickcolor.utils.ShareUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 收藏界面
 */
public class CollectActivity extends AppCompatActivity {

    private List<Color> mColorList = new ArrayList<>();
    private ColorAdapter mColorAdapter;
    private RecyclerView mRecyclerView;
    private RefreshLayout mRefreshLayout;
    private GridLayoutManager mGridLayoutManager;
    private Context mContext;
    private Handler mHandler;
    private static final int DATA_CHANGED = 1;
    private MyObserver mMyObserver;

    private Handler mHandlerContentResolver = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DATA_CHANGED:
                    mColorAdapter.clearList();
                    initData();
                default:
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_collect);
        getSupportActionBar().setTitle(getResources().getString(R.string.collect));

        // 显示返回键
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        // 初始化视图
        initView();

        // 初始化数据
        initData();
        Uri uri = Uri.parse("content://com.thundersoft.pickcolor.provider/color");
        mMyObserver = new MyObserver(mHandlerContentResolver);

        /**
         * 注册内容观察者
         * uri:该监听器所监听的ContentProvider的Uri
         * notifyForDescendants:为true时，假如注册监听的uri为content://abc，
         *      content://abc/ayz、content://abc/xyz的数据改变也会触发该监听器
         * observer:监听器实例
         */
        this.getContentResolver().registerContentObserver(uri,true,mMyObserver);
    }

    private void initView() {
        mContext = this;
        mHandler = new Handler();
        mRefreshLayout = findViewById(R.id.collect_refresh_layout);
        mRecyclerView = findViewById(R.id.collect_recycler_view);
        mGridLayoutManager = new GridLayoutManager
                (mContext,3,GridLayoutManager.VERTICAL,false);
        mRecyclerView.setLayoutManager(mGridLayoutManager);
        mColorAdapter = new ColorAdapter(mContext);
        mRecyclerView.setAdapter(mColorAdapter);

        //下拉刷新
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mColorAdapter.clearList();
                        initData();
                        mRefreshLayout.finishRefresh();
                    }
                });
            }
        });

        // 上拉加载更多（未实现）
        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mRefreshLayout.finishLoadMore();
                    }
                });
            }
        });

        mRefreshLayout.setEnableLoadMore(true);
        mRefreshLayout.autoRefresh();

    }

    private void initData() {
        mColorList.clear();
        queryData();
    }

    private void queryData() {
        // 查询数据
        Uri uri = Uri.parse("content://com.thundersoft.pickcolor.provider/color");
        Cursor cursor = null;
        try {
            cursor = mContext.getContentResolver().query(uri,null,
                    "kind = ? and userId = ?",new String[]{getResources().getString(R.string.collect),
                    String.valueOf(ShareUtils.getInt(mContext,"userId",0))},null);

            // 设置类中的部分item
            if(cursor !=null){
                while(cursor.moveToNext()){
                    int id = cursor.getInt(cursor.getColumnIndex("id"));
                    String hexValue = cursor.getString(cursor.getColumnIndex("hexValue"));
                    int rValue = cursor.getInt(cursor.getColumnIndex("rValue"));
                    int gValue = cursor.getInt(cursor.getColumnIndex("gValue"));
                    int bValue = cursor.getInt(cursor.getColumnIndex("bValue"));
                    String describe = cursor.getString(cursor.getColumnIndex("describe"));
                    Color color = new Color(id,Color.TYPE_TWO,rValue, gValue, bValue, hexValue, describe);
                    mColorList.add(color);
                }
            }
            mColorAdapter.addList(mColorList);
            mColorAdapter.notifyDataSetChanged();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(cursor !=null){
                cursor.close();
            }
        }
    }

    // ContentObserver监听数据库变化
    class MyObserver extends ContentObserver{
        private Handler handler;
        public MyObserver(Handler handler) {
            super(handler);
            this.handler = handler;
        }

        /**
         * 当它监听的ContentProvider数据发送改变的时候，该方法被触发。
         */
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            handler.sendEmptyMessage(DATA_CHANGED);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        // 注销监听器
        this.getContentResolver().unregisterContentObserver(mMyObserver);
    }

    // 菜单栏操作
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}
